package com.boot.system.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.system.dto.SysMenuDTO;
import com.boot.system.entity.SysMenuEntity;
import com.boot.system.mapper.SysMenuMapper;
import com.boot.system.wrapper.SysMenuWrapper;
import com.boot.system.service.ISysMenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yangfan
 * @date 2023/12/22
 * @Description
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements ISysMenuService {

    @Override
    public List<SysMenuDTO> selectList(Map<String, Object> params) {
        //TODO 根据角色获取菜单
        List<SysMenuEntity> list = baseMapper.selectList(Wrappers.lambdaQuery(SysMenuEntity.class).orderByAsc(SysMenuEntity::getSortOrder));
        return streamToTree(SysMenuWrapper.build().listDTO(list), "0");
    }

    @Override
    public List<SysMenuDTO> selectListByRoleIds(SysMenuDTO sysMenuDTO, List<String> roleIds) {
        return SysMenuWrapper.build().listDTO(baseMapper.selectListByRoleIds(sysMenuDTO, roleIds));
    }

    public static List<SysMenuDTO> streamToTree(List<SysMenuDTO> menuDTOS, String parentId) {
        return menuDTOS.stream()
                // 过滤父节点
                .filter(parent -> parent.getParentId().equals(parentId))
                // 把父节点children递归赋值成为子节点
                .peek(child -> child.setChildren(streamToTree(menuDTOS, child.getMenuId()))).collect(Collectors.toList());
    }
}
